<?php
ptaste();
require_once(dirname(__FILE__)."/utils.php");

class JEngDBImage extends JEngUtilHelper
{
	function processLoaded($fname,$sx=0,$sy=0,$oldid=0)
	{
		$logger=$this->utils()->site()->logger();
		if (!isset($_FILES[$fname]))
		  return 0;
		@list($width, $height, $type, $attr) = getimagesize($_FILES[$fname]['tmp_name']);
		if ($type==3)
			$img=imagecreatefrompng($_FILES[$fname]['tmp_name']);
		else if ($type==2)
			$img=imagecreatefromjpeg($_FILES[$fname]['tmp_name']);
		else if ($type==1)
			$img=imagecreatefromgif($_FILES[$fname]['tmp_name']);
		else return 0;
		if (!$img) return 0;
		if ($sx!=0 && $sy!=0 && ($sx!=$width || $sy!=$height))
		{
		  $oimg=$img;
		  $img=imagecreatetruecolor($sx, $sy);
		  imagecopyresampled($img,$oimg,0,0,0,0,$sx,$sy,$width,$height);
		  imagedestroy($oimg);
		  $width=$sx;
		  $height=$sy;
		}
		imagejpeg($img,$_FILES[$fname]['tmp_name'],75);
		imagedestroy($img);
		if ($oldid!=0)
		{
		  $qry="UPDATE uimages SET data='%s',width=%d,height=%d WHERE id=".$oldid.";";
		}else{
		  $qry="INSERT INTO uimages(data,width,height) VALUES('%s',%d,%d);";
		}
		$db=$this->utils()->site()->common_db();
		$imdata=$db->unhack(file_get_contents($_FILES[$fname]['tmp_name']));
		$db->queryf($qry,$imdata,$width,$height);
		if ($oldid==0)
		  $oldid=$db->lastid();
		return $oldid;
	}
	
	function getImageData($id)
	{
		$res=$this->utils()->site()->common_db()->queryf("SELECT width,height,code FROM uimages WHERE id=%d;",$id);
		if (!$res) return false;
		$rw=$res->next();
		if (!$rw) return false;
		return array($rw[0],$rw[1],$rw[2]?$rw[2]:"");
	}
	
	function printImage($id,$expires=24)
	{
		$res=$this->utils()->site()->common_db()->queryf("SELECT data FROM uimages WHERE id=%d;",$id);
		if (!$res) return false;
		$rw=$res->next();
		if (!$rw) return false;
		if (!$rw[0]) return false;
		header('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT',true, 200);
		header('Expires: '.gmdate('D, d M Y H:i:s',  time() + $expires).' GMT',true, 200);
		header('Content-Length: '.strlen($rw[0]));
		header("Content-type: image/jpeg");
		echo $rw[0];
	}
}

?>